import { history, useModel } from '@umijs/max';
import { Badge, Button, Card, Descriptions, Spin, Tag, theme } from 'antd';
import React, { useEffect, useState } from 'react';
import { getInterfaceInfoVoByIdUsingGet } from '@/services/api/interfaceInfoController';
import { useParams } from '@@/exports';
import Paragraph from 'antd/lib/typography/Paragraph';
import { InterfaceRequestMethodEnum, statusEnum } from '@/enum/commonEnum';
import './index.less';
import { BugOutlined, CodeOutlined, FileTextOutlined } from '@ant-design/icons';
import ApiTab from '@/pages/Interface/InterfaceInfoDetail/components/ApiTab';
import ToolsTab from '@/pages/Interface/InterfaceInfoDetail/components/ToolsTab';
import SampleCodeTab from '@/pages/Interface/InterfaceInfoDetail/components/SampleCodeTab';
import { getUserInterfaceInfoByInterfaceInfoIdUsingGet } from '@/services/api/userInterfaceInfoController';

const InterfaceInfoDetailPage: React.FC = () => {
  const { token } = theme.useToken();
  const { initialState } = useModel('@@initialState');

  const [interfaceInfo, setInterfaceInfo] = useState<API.InterfaceInfoVO>();
  const [requestParams, setRequestParams] = useState<API.RequestParamsField[]>([]);
  const [responseParams, setResponseParams] = useState<API.ResponseParamsField[]>([]);

  const [loading, setLoading] = useState<boolean>(false);
  const params = useParams();
  const [activeTabKey, setActiveTabKey] = useState<
    'tools' | 'api' | 'errorCode' | 'sampleCode' | string
  >('api');

  const tabListNoTitle = [
    {
      key: 'api',
      label: (
        <>
          <FileTextOutlined />
          API文档
        </>
      ),
    },
    {
      key: 'tools',
      label: (
        <>
          <BugOutlined />
          在线调试工具
        </>
      ),
    },
    // {
    //   key: 'errorCode',
    //   label: (
    //     <>
    //       <FileExclamationOutlined />
    //       错误码参照
    //     </>
    //   ),
    // },
    {
      key: 'sampleCode',
      label: (
        <>
          <CodeOutlined />
          示例代码
        </>
      ),
    },
  ];

  const contentListNoTitle: Record<string, React.ReactNode> = {
    api: (
      <ApiTab
        requestParams={requestParams}
        responseParams={responseParams}
        returnCode={interfaceInfo?.returnFormat ?? ''}
        errorCodeTab={() => {}}
        sampleCode={() => {}}
      />
    ),
    tools: <ToolsTab interfaceInfo={interfaceInfo} requestParams={requestParams} />,
    sampleCode: <SampleCodeTab interfaceInfo={interfaceInfo} errorCodeTab={() => {}} />,
  };

  const onTabChange = (key: string) => {
    setActiveTabKey(key);
  };

  const loadUserInterfaceInfo = async () => {
    if (params.id) {
      await getUserInterfaceInfoByInterfaceInfoIdUsingGet({ interfaceInfoId: params.id as any });
    }
  };

  const load = async () => {
    setLoading(true);
    try {
      if (params.id) {
        const res = await getInterfaceInfoVoByIdUsingGet({ id: params.id as any });

        if (res.data) {
          setInterfaceInfo(res.data);
          // eslint-disable-next-line no-eval
          setRequestParams(res.data.requestParams ?? []);
          // eslint-disable-next-line no-eval
          setResponseParams(res.data.responseParams ?? []);
          loadUserInterfaceInfo();
        }
      }
    } catch (e) {}
    setLoading(false);
  };

  useEffect(() => {
    load();
  }, []);

  return (
    <>
      <Spin spinning={loading}>
        <Card
          title={interfaceInfo?.name}
          extra={
            <Button
              type={'primary'}
              onClick={() => {
                history.back();
              }}
            >
              返回
            </Button>
          }
        >
          <Descriptions>
            <Descriptions.Item key={'url'} label={'接口地址'}>
              <Paragraph copyable>{`${interfaceInfo?.host}${interfaceInfo?.url}`}</Paragraph>
            </Descriptions.Item>
            <Descriptions.Item key={'returnFormat'} label={'返回格式'}>
              <Paragraph copyable>{interfaceInfo?.returnFormat ?? 'JSON'}</Paragraph>
            </Descriptions.Item>
            <Descriptions.Item key={'reduceScore'} label={'消耗积分/次'}>
              {interfaceInfo?.reduceScore ?? 0}
            </Descriptions.Item>
            <Descriptions.Item key={'method'} label={'请求方式'}>
              <Tag color={InterfaceRequestMethodEnum[interfaceInfo?.method ?? 'default']}>
                {interfaceInfo?.method}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item key={'totalInvoke'} label={'调用次数'}>
              {interfaceInfo?.totalInvoke ?? 0}次
            </Descriptions.Item>
            <Descriptions.Item key={'status'} label={'接口状态'}>
              {interfaceInfo && interfaceInfo.status === 0 ? (
                <Badge status="default" text={statusEnum[interfaceInfo.status]} />
              ) : null}
              {interfaceInfo && interfaceInfo.status === 1 ? (
                <Badge status="processing" text={statusEnum[interfaceInfo.status]} />
              ) : null}
              {interfaceInfo && interfaceInfo.status === 2 ? (
                <Badge status="error" text={statusEnum[interfaceInfo.status]} />
              ) : null}
            </Descriptions.Item>
            <Descriptions.Item key={'description'} label="接口描述">
              {interfaceInfo?.description ?? '该接口暂无描述信息'}
            </Descriptions.Item>
          </Descriptions>
        </Card>
        <br />
        <Card>
          <p className="highlightLine">接口详细描述请前往开发者文档查看：</p>
          <a
            href={`/pages/${interfaceInfo?.id}/#${interfaceInfo?.name}`}
            target={'_blank'}
            rel="noreferrer"
          >
            开发者文档：{interfaceInfo?.name}
          </a>
        </Card>
        <br />
        <Card
          style={{ width: '100%' }}
          tabList={tabListNoTitle}
          activeTabKey={activeTabKey}
          onTabChange={onTabChange}
          tabProps={{
            size: 'middle',
          }}
        >
          {contentListNoTitle[activeTabKey]}
        </Card>
      </Spin>
    </>
  );
};

export default InterfaceInfoDetailPage;
